package cn.cool.springframework.beans.factory.support;

import cn.cool.springframework.beans.BeansException;
import cn.cool.springframework.beans.PropertyValue;
import cn.cool.springframework.beans.PropertyValues;
import cn.cool.springframework.beans.factory.config.BeanDefinition;
import cn.cool.springframework.beans.factory.config.BeanReference;
import cn.hutool.core.bean.BeanUtil;
import lombok.Data;

import java.lang.reflect.Constructor;

@Data
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

    private final InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();

    /**
     * 反射去创建 bean（但是要分是cglib创建还是jdk反射创建）
     */
    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        // 获取 bean定义信息中的class对象，创建对象并且返回
        Object bean = null;
        try {
            // Bean生命周期 第一步：实例化
            bean = createBeanInstance(beanDefinition, beanName, args);
            // Bean生命周期 第二步：属性填充
            applyPropertyValues(beanName, bean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }

        // 缓存单例对象
        addSingleton(beanName, bean);
        return bean;
    }

    /**
     * 属性填充
     */
    protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();

                // 如果 Bean是引用类型，那么就尝试getBean(属性)
                if (value instanceof BeanReference) {
                    // A 依赖 B，获取 B的实例化对象
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getBeanName());
                }
                // 属性填充
                BeanUtil.setFieldValue(bean, name, value);
            }
        } catch (Exception e) {
            throw new BeansException("Error setting property values: " + beanName);
        }
    }

    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) {
        Constructor constructorToUse = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor<?> ctor : declaredConstructors) {
            if (args != null && ctor.getParameterTypes().length == args.length) {
                constructorToUse = ctor;
                break;
            }
        }
        return getInstantiationStrategy().instantiate(beanDefinition, beanName, constructorToUse, args);
    }
}